﻿using System;
using System.IO.Ports;


namespace ComTest
{
    public class SerialPortHandler
    {
        private SerialPort _port = new SerialPort("COM1", 9600, Parity.None, 8, StopBits.One);
        private string _receivedMsg = "";

        public SerialPortHandler()
        {
            _port.DataReceived += _dataReceived;
            _port.Open();
        }

        public void Write(string s)
        {
            _port.WriteLine(s);
        }

        private void _dataReceived(object sender, SerialDataReceivedEventArgs e)
        {
            _receivedMsg = _port.ReadExisting();
            if (_receivedMsg.Contains("\n"))   //this means we have received a full sentence
            {
                Console.WriteLine(_receivedMsg);
                _receivedMsg = "";
            }
        }
    }
}
